﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace MediaController.Configuration
{
    /// <summary>
    /// This Configuration class is basically just a set of 
    /// properties with a couple of static methods to manage
    /// the serialization to and deserialization from a
    /// simple XML file.
    /// </summary>
    [Serializable]
    public class Configuration<T>
    {
        public virtual void Serialize(string file)
        {
            var xs = new XmlSerializer(typeof(T));
            var fullPath = GetFullPath(file);
            StreamWriter writer = File.CreateText(fullPath);
            xs.Serialize(writer, this);
            writer.Flush();
            writer.Close();
        }

        public virtual T Deserialize(string file)
        {
            var xs = new XmlSerializer(typeof(T));
            if (!File.Exists(file)) return default(T);

            var fullPath = GetFullPath(file);

            StreamReader reader = File.OpenText(fullPath);
            var c = (T)xs.Deserialize(reader);
            reader.Close();
            return c;
        }

        /// <summary>
        /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
        /// </summary>
        /// <param name="characters">Unicode Byte Array to be converted to String</param>
        /// <returns>String converted from Unicode Byte Array</returns>
        private String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        /// <summary>
        /// Converts the String to UTF8 Byte array and is used in De serialization
        /// </summary>
        /// <param name="pXmlString"></param>
        /// <returns></returns>
        private Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }

        private string GetFullPath(string fileName)
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var path = Path.Combine(currentDirectory, fileName);
            return path;
        }
    }
}
